from flask import Blueprint, render_template, request

from applications.common import curd
from applications.common.curd import model_to_dicts
from applications.common.helper import ModelFilter
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import xss_escape
from applications.extensions import db
from applications.models import Role, Equipment
from applications.schemas import EquipmentOutSchema

admin_equipment = Blueprint('adminEquipment', __name__, url_prefix='/admin/equipment')


# 设备管理
@admin_equipment.get('/')
#@authorize("admin:user:main", log=True)
def main():
    return render_template('admin/equipment/main.html')

# 设备分页查询
@admin_equipment.get('/data')
def data():
    # 获取请求参数
    id = request.args.get('id', type=int)
    Name = xss_escape(request.args.get('Name', type=str))
    Equid = xss_escape(request.args.get('Equid', type=str))
    Version = xss_escape(request.args.get('Version', type=str))
    Equadmin = xss_escape(request.args.get('Equadmin', type=str))
    enable = request.args.get('enable', type=int)

    # 查询参数构造
    mf = ModelFilter()
    if id:
        mf.exact(field_name="id", value=id)
    if enable:
        mf.exact(field_name="enable", value=enable)
    if Name:
        mf.contains(field_name="Name", value=Name)
    if Equid:
        mf.contains(field_name="Equid", value=Equid)
    if Version:
        mf.contains(field_name="Version", value=Version)
    if Equadmin:
        mf.contains(field_name="Equadmin", value=Equadmin)
    # orm查询
    # 使用分页获取data需要.items
    equipment = Equipment.query.filter(mf.get_filter(model=Equipment)).layui_paginate()
    count = equipment.total
    # 返回api
    return table_api(data=model_to_dicts(schema=EquipmentOutSchema, data=equipment.items), count=count)

# 设备增加
@admin_equipment.get('/add')
#@authorize("admin:equipment:add", log=True)
def add():
    roles = Role.query.all()
    return render_template('admin/equipment/add.html', roles=roles)


@admin_equipment.post('/save')
#@authorize("admin:equipment:add", log=True)
def save():
    req_json = request.json
    a = req_json.get("roleIds")
    Name = xss_escape(req_json.get('Name'))
    Equid = xss_escape(req_json.get('Equid'))
    Version = xss_escape(req_json.get('Version'))
    Equadmin = xss_escape(req_json.get('Equadmin'))
    role_ids = a.split(',')

    if not Name or not Equid or not Version or not Equadmin:
        return fail_api(msg="设备名字、设备编号、设备版本不得为空")

    if bool(Equipment.query.filter_by(Name=Name).count()):
        return fail_api(msg="设备已经存在")
    equipment = Equipment(Name=Name, Equid=Equid, Version=Version, Equadmin=Equadmin)
    db.session.add(equipment)
    roles = Role.query.filter(Role.id.in_(role_ids)).all()
    for r in roles:
        equipment.role.append(r)
    db.session.commit()
    return success_api(msg="增加成功")


# 删除设备
@admin_equipment.delete('/remove/<int:id>')
@authorize("admin:equipment:remove", log=True)
def delete(id):
    user = Equipment.query.filter_by(id=id).first()
    user.role = []

    res = Equipment.query.filter_by(id=id).delete()
    db.session.commit()
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")

#  编辑设备
@admin_equipment.get('/edit/<int:id>')
@authorize("admin:equipment:edit", log=True)
def edit(id):
    equipment = curd.get_one_by_id(Equipment, id)
    roles = Role.query.all()
    checked_roles = []
    for r in roles:
        checked_roles.append(r.id)
    return render_template('admin/equipment/edit.html', equipment=equipment, roles=roles, checked_roles=checked_roles)


#  编辑设备
@admin_equipment.put('/update')
@authorize("admin:equipment:edit", log=True)
def update():
    req_json = request.json
    a = req_json.get("roleIds")
    id = xss_escape(req_json.get("id"))
    Name = xss_escape(req_json.get('Name'))
    Equid = xss_escape(req_json.get('Equid'))
    Version = xss_escape(req_json.get('Version'))
    Equadmin = xss_escape(req_json.get('Equadmin'))
    role_ids = a.split(',')
    Equipment.query.filter_by(id=id).update({'Name': Name, 'Equid': Equid, 'Version': Version, 'Equadmin': Equadmin})
    u = Equipment.query.filter_by(id=id).first()

    roles = Role.query.filter(Role.id.in_(role_ids)).all()
    u.role = roles

    db.session.commit()
    return success_api(msg="更新成功")


# 批量删除
@admin_equipment.delete('/batchRemove')
@authorize("admin:equipment:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        user = Equipment.query.filter_by(id=id).first()
        user.role = []

        res = Equipment.query.filter_by(id=id).delete()
        db.session.commit()
    return success_api(msg="批量删除成功")